package com.song.bloomfilter.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.song.bloomfilter.domain.Products;
import com.song.bloomfilter.service.ProductsService;
import com.song.bloomfilter.mapper.ProductsMapper;
import com.song.bloomfilter.util.BloomFilterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Random;

/**
* @author Szx
* @description 针对表【products】的数据库操作Service实现
* @createDate 2025-03-14 20:45:32
*/
@Service
public class ProductsServiceImpl extends ServiceImpl<ProductsMapper, Products>
    implements ProductsService{

    @Autowired
    private BloomFilterUtil bloomFilterUtil;
    @Override
    public Products queryGoodsWithBloomFilter(Long id) {
        //判断是否在过滤器里面
        boolean b = bloomFilterUtil.getCacheBloomFilter(id);
        if (!b){
            //不在直接返回null
            return null;

        }
        //获取该缓存是否存在如果不存在则去数据库查
        Products info = bloomFilterUtil.getInfo(id);
        if (info == null){
            System.out.println("触发数据库查询");
            Products byId = getById(id);
            if (byId == null){
                return null;
            }
            return byId;
        }
        return info;
    }

    @Override
    public void insert30() {
        Random random = new Random();

        for (int i=0;i<100;i++){
           new Thread(()->{
               Products products = new Products();
               products.setPrice(BigDecimal.valueOf(random.nextDouble() * 100));
               products.setProductName("小米"+ random.nextInt(0,1024*1024));
               save(products);
               //先添加到布隆过滤器
               bloomFilterUtil.cacheBloomFilter(products.getProductId());

               //然后把自身缓存
               bloomFilterUtil.cacheInfo(products);
               System.out.println(products);
           }).start();
        }
    }
}




